package com.jhy.new2025.BinaryTree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * 给定一个非空二叉树的根节点 root , 以数组的形式返回每一层节点的平均值。
 * 与实际答案相差 10-5 以内的答案可以被接受。
 */
public class AverageOfLevels {

    public List<Double> averageOfLevels(TreeNode root) {
        // 存储结果
        List<Double> doubles = new ArrayList<>();
        ArrayDeque<TreeNode> deque = new ArrayDeque<>();
        if (root == null) return doubles;
        deque.offer(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            double count = deque.size();
            double temp = 0;
            while (size > 0) {
                TreeNode pop = deque.poll();
                int val = pop.val;
                temp += val;
                if (pop.left != null) deque.offer(pop.left);
                if (pop.right != null) deque.offer(pop.right);
                size--;
            }
            double a = temp/count;
            doubles.add(a);
        }
        return doubles;
    }
}
